from datetime import datetime, timedelta
import jwt
from configurations import settings
from .validation import LoginValidation, LoginForm, LoginResult
from ...models import SysUser


class LoginManage:
    """
    登录认证工具
    """

    @LoginValidation
    async def password_login(self, data: LoginForm, user: SysUser, **kwargs) -> LoginResult:
        """
        验证用户密码
        """
        result = SysUser.verify_password(data.password, user.password)
        if result:
            return LoginResult(status=True, msg="验证成功")
        return LoginResult(status=False, msg="账号或密码错误")

    @staticmethod
    def create_token(payload: dict, expires: timedelta = None):
        """
        创建一个生成新的访问令牌的工具函数。

        pyjwt：https://github.com/jpadilla/pyjwt/blob/master/docs/usage.rst
        jwt 博客：https://geek-docs.com/python/python-tutorial/j_python-jwt.html

        #TODO 传入的时间为UTC时间datetime.datetime类型，但是在解码时获取到的是本机时间的时间戳
        """
        if expires:
            expire = datetime.utcnow() + expires
        else:
            expire = datetime.utcnow() + timedelta(hours=settings.TOKEN_EXPIRE_HOUR)
        payload.update({"exp": expire})
        encoded_jwt = jwt.encode(payload, settings.TOKEN_SECRET_KEY, algorithm=settings.ALGORITHM)
        return encoded_jwt
